package com.shujia

import scala.io.{BufferedSource, Source}

object Demo29Student {
  def main(args: Array[String]): Unit = {
    /**
     * 2、统计每个班级学生的人数
     */
    //读取数据
    val bufferedSource: BufferedSource = Source.fromFile("scala/data/students.csv")
    val lines: List[String] = bufferedSource.getLines().toList

    //解析数据
    val students: List[(String, String, Int, String, String)] = lines
      .map(line => {
        val split: Array[String] = line.split(",")
        val id: String = split(0)
        val name: String = split(1)
        val age: Int = split(2).toInt
        val sex: String = split(3)
        val clazz: String = split(4)
        (id, name, age, sex, clazz)
      })

    //按照班级分组
    val groupByList: Map[String, List[(String, String, Int, String, String)]] = students
      .groupBy {
        case (id, name, age, sex, clazz) => clazz
      }

    //再组内计算班级的人数
    val clazzNum: Map[String, Int] = groupByList
      .map {
        case (clazz, list) =>
          val num: Int = list.length
          (clazz, num)
      }

    clazzNum.foreach(println)

  }
}
